//
//  LoginViewController.m
//  MemberProject
//
//  Created by MAC OS X on 15/4/1.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "LoginViewController.h"
#import "QRCodeReaderViewController.h"
#import "QRCodeReader.h"
#import "BaseNavigationController.h"
#import "SignViewController.h"
#import "QRcodeViewController.h"
#import "IQKeyboardManager.h"
#import "ZBarReaderViewController.h"
#import "SignInputViewController.h"
#import "SignForgetPdViewController.h"
#import "MenuViewController.h"
#import "ModelUser.h"
#import "UserInfoManager.h"
#import "QRCodeGenerator.h"
#import "ModelGroup.h"
#import "Countly.h"
#import "BuaatVolunteerServerSDK.h"
#import "CityFileManager.h"
#import "VolunteerClaimViewController.h"

#define NumberKeyBoardHeight 220
@interface LoginViewController ()<QRCodeReaderDelegate>
//{
//    AFHTTPRequestOperation *workingOperation;
//}
@property (assign,nonatomic)int sign;
@property (nonatomic,strong ) AFHTTPRequestOperation *operation;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupView];
    [IQKeyboardManager sharedManager].enable = NO;
    if (SCREEN_HEIGHT<568) {
        self.loginHeight.constant = NumberKeyBoardHeight;
    }
    self.title = @"登陆";



    
    
    [[Countly sharedInstance]startOnCloudWithAppKey:@"f99391e9d74dac5d84a442d6a0c2ea0b154b822e"];
    
    

    
}

-(SecKeyRef)getPublicKey:str{
//    NSData *certificateData = [GTMBase64 decodeString:RSA_KEY_BASE64];//这里解base64
    

    NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:0];
    
    SecCertificateRef myCertificate = nil;
    myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)data);
    SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
    SecTrustRef myTrust;
    OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);
    if (status != 0) {
        NSLog(@"SecTrustCreateWithCertificates fail. Error Code: %ld", status);
        return nil;
    }
    SecTrustResultType trustResult;
    if (status == noErr) {
        status = SecTrustEvaluate(myTrust, &trustResult);
    }
    
    return SecTrustCopyPublicKey(myTrust);
}

-(NSString *)RSAEncrypotoTheData:(NSString *)plainText
{
    
    SecKeyRef publicKey=nil;
    publicKey=[self getPublicKey:plainText];
    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    uint8_t *cipherBuffer = NULL;
    
    cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
    memset((void *)cipherBuffer, 0*0, cipherBufferSize);
    
    NSData *plainTextBytes = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    int blockSize = cipherBufferSize-11;  // 这个地方比较重要是加密数组长度
    int numBlock = (int)ceil([plainTextBytes length] / (double)blockSize);
    NSMutableData *encryptedData = [[NSMutableData alloc] init];
    for (int i=0; i<numBlock; i++) {
        int bufferSize = MIN(blockSize,[plainTextBytes length]-i*blockSize);
        NSData *buffer = [plainTextBytes subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
        OSStatus status = SecKeyEncrypt(publicKey,
                                        kSecPaddingPKCS1,
                                        (const uint8_t *)[buffer bytes],
                                        [buffer length],
                                        cipherBuffer,
                                        &cipherBufferSize);
        if (status == noErr)
        {
            NSData *encryptedBytes = [[NSData alloc]
                                       initWithBytes:(const void *)cipherBuffer
                                       length:cipherBufferSize];
            [encryptedData appendData:encryptedBytes];
        }
        else
        {
            return nil;
        }
    }
    if (cipherBuffer)
    {
        free(cipherBuffer);
    }
    NSString *encrypotoResult=[NSString stringWithFormat:@"%@",[encryptedData  base64EncodedStringWithOptions:0]];
    
    return encrypotoResult;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotification:)
                                                 name:SVProgressHUDDidTouchDownInsideNotification
                                               object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SVProgressHUDDidTouchDownInsideNotification object:nil];
}
#pragma mark 点击取消等待界面
- (void)handleNotification:(NSNotification *)notif
{
    [SVProgressHUD dismiss];
    [self.workingOperation cancel];
}

-(void)setupView
{
    self.pdWidth.constant = SCREEN_WIDTH/2-1;
    self.signWidth.constant = SCREEN_WIDTH/2-1;
    
    
    for (int i=11; i<13; i++) {
        UIView *view = [self.inputView viewWithTag:i];
        view.layer.borderWidth = 0.8;
        view.layer.cornerRadius = 5;
        view.layer.borderColor = [UIColor whiteColor].CGColor;
    }
    
    
    UIButton *btn = (UIButton *)[self.view viewWithTag:22];
    btn.layer.cornerRadius = 5;
    
    [self.telField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.pdField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];//修改颜色
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelEdit)];
    [self.view addGestureRecognizer:tap];
    
    
    [self.cancelBackLoginBtn addTarget:self action:@selector(cancelLogin:) forControlEvents:64];
    
    
    
    
}

-(void)getBack:(backHomeBlock)block
{
    self.bBlock = block;
}

-(void)cancelLogin:(UIButton *)sender
{
    if (self.isNeedToPopHome)
    {
        self.bBlock();
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)cancelEdit
{
    [self.telField resignFirstResponder];
    [self.pdField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 注册先扫描二维码
- (IBAction)SignAction:(id)sender {

//    [self pushSignViewController:@"" andGroupId:@""];
    [self showQz:SignZbarStyle];
    [self getZBarPushBlockStr:^(NSString *str) {
        [self checkGroupInfo:str];
    }];
//
}
- (IBAction)forgetAction:(id)sender
{
//    [self pushSignViewController:@"" andGroupId:@""];
    SignForgetPdViewController *signFpdVC = [[SignForgetPdViewController alloc]initWithNibName:@"SignForgetPdViewController" bundle:nil];
    BaseNavigationController *baseNC = [[BaseNavigationController alloc]initWithRootViewController:signFpdVC];
    [self presentViewController:baseNC animated:YES completion:nil];
}
-(void)checkGroupInfo:(NSString *)groupCode
{
    [SVProgressHUD showWithStatus:@"扫描中。。" maskType:SVProgressHUDMaskTypeBlack];
    [[BuaatVolunteerServerSDK sharedInstance]requestQrcodeGroupInfoWithGroupCode:groupCode success:^(NSHTTPURLResponse *response, id responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            id result = responseObject[@"result"];
            if ([result isKindOfClass:[NSDictionary class]]) {
                NSString *groupCode = result[@"groupCode"];
                NSString *groupName = result[@"groupName"];
                [self pushSignViewController:groupName andGroupCode:groupCode];
                
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"没有该机构" maskType:SVProgressHUDMaskTypeBlack];
            }
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"没有该机构" maskType:SVProgressHUDMaskTypeBlack];
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeBlack];
        
    }];
    
    
    
   
}

#pragma mark 推到注册界面
-(void)pushSignViewController:(NSString *)name andGroupCode:(NSString *)groupCode
{
    SignViewController *signVC = [[SignViewController alloc]initWithNibName:@"SignViewController" bundle:nil];
    [signVC setGroupName:name];
    [signVC setGroupCode:groupCode];
    BaseNavigationController *baseNC = [[BaseNavigationController alloc]initWithRootViewController:signVC];
    [self presentViewController:baseNC animated:YES completion:nil];
}
#pragma mark 验证信息
-(BOOL)isInfoRight
{
    if ([self.telField.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请填入手机号" maskType:SVProgressHUDMaskTypeBlack];
        return 0;
    }
    
    if (![Utils validateMobile:self.telField.text]) {
//        [Utils showAlert:@"手机号码不正确"];
        [SVProgressHUD showErrorWithStatus:@"手机号码不正确" maskType:SVProgressHUDMaskTypeBlack];
        return 0;
    }
    
    if (self.pdField.text.length<6) {
        [SVProgressHUD showErrorWithStatus:@"密码长度应不小于6位" maskType:SVProgressHUDMaskTypeBlack];
//        [Utils showAlert:@"密码长度小于6位"];
        return 0;
    }
    
    return 1;
}
#pragma mark 登陆
- (IBAction)LoginAction:(id)sender{
//    [SVProgressHUD showWithStatus:@"正在登陆" maskType:SVProgressHUDMaskTypeBlack];
//    [self cancelEdit];
//    if ([self isInfoRight]) {
//        NSString *pdStr = self.pdField.text;
//        NSString *pdMD5Str = [Utils md5:pdStr];
//        NSDictionary *parameters = @{@"token":@"sdfsadfsadfasdf",@"module":@"Voluteer",@"method":@"verifyVoluteerLogin",@"requestId":[NSNull new],@"requestParam":@[self.telField.text,pdMD5Str]};
//
//       self.workingOperation = [Utils requestDic:parameters andRusult:^(id result) {
//           if ([result isKindOfClass:[NSDictionary class]]) {
//               NSDictionary *responseData = result[@"responseData"];
//               if ([responseData isKindOfClass:[NSDictionary class]]) {
//                   NSNumber *status = responseData[@"status"];
//                   if (status.intValue!=-1) {
//                       ModelUser *user = [ModelUser getUserForDic:responseData];
//                       [UserInfoManager sharedManager].modelMser = user;
//                       [self loginFinish:responseData];
//                       [SVProgressHUD dismiss];
//                   }else{
//                       [SVProgressHUD showErrorWithStatus:@"密码错误" maskType:SVProgressHUDMaskTypeBlack];
//                   }
//               }else{
//                   [SVProgressHUD showErrorWithStatus:@"该手机号还没注册"];
//               }
//           }else{
//               [SVProgressHUD showErrorWithStatus:@"网络错误"];
//           }
//        } andError:^(id result) {
//            [SVProgressHUD showErrorWithStatus:@"网络错误" maskType:SVProgressHUDMaskTypeBlack];
//        }];
//    }
    
    
    
        [SVProgressHUD showWithStatus:@"正在登陆" maskType:SVProgressHUDMaskTypeBlack];
        [self cancelEdit];
        if ([self isInfoRight]) {
    NSString *pdStr = self.pdField.text;
    NSString *pdMD5Str = [Utils md5:pdStr];
    NSString *telStr = [[BuaatVolunteerServerSDK sharedInstance]encryptStrWithPublicKey:self.telField.text];
            
//    NSString *pdMD5Str = @"e10adc3949ba59abbe56e057f20f883e";275382
    [[BuaatVolunteerServerSDK sharedInstance]requestAuthVolunteerWithVolunteerMobile:telStr volunteerPwd:pdMD5Str success:^(NSHTTPURLResponse *response, id responseObject) {
        //密码正确
        [SVProgressHUD dismiss];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            id resultDic = responseObject[@"result"];
            if ([resultDic isKindOfClass:[NSDictionary class]]) {
                ModelUser *user = [ModelUser getUserForDic:resultDic];
                [UserInfoManager sharedManager].modelMser = user;
                [UserInfoManager sharedManager].modelMser.loginPassword = pdMD5Str;
                NSMutableDictionary *changeDic = [[NSMutableDictionary alloc]initWithDictionary:resultDic];
                [changeDic setValue:pdMD5Str forKey:@"loginPassword"];
                
                [self loginFinish:changeDic];
                [SVProgressHUD dismiss];
            }else
            {
                id ret = responseObject[@"ret"];
                if ([ret isKindOfClass:[NSNumber class]]) {
                    NSNumber *num = ret;
                    if (num.intValue==1103) {
                        [SVProgressHUD showErrorWithStatus:@"密码错误" maskType:SVProgressHUDMaskTypeBlack];
                    }else
                        //该用户还没注册
                        [SVProgressHUD showErrorWithStatus:@"该手机号还没注册" maskType:SVProgressHUDMaskTypeBlack];
                }
                 
            }
            
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        
    }];
        }
     
}



-(void)loginFinish:(NSDictionary *)userDic
{
    //已登录
    [[NSUserDefaults standardUserDefaults]setValue:loginYES forKey:ISAlreadyLogin];
    [[UserInfoManager sharedManager]writeLocalLog:userDic];
    
    
    
    //设置保单
    [[UserInsuranceManager sharedManager]setupUserInsurance:^{
        
    }];
    
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationLoginChangeInfo object:nil];
    }];
    
}
#pragma mark - QRCodeReader Delegate Methods

- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result
{
    [self dismissViewControllerAnimated:YES completion:^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"QRCodeReader" message:result delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }];
}

- (void)readerDidCancel:(QRCodeReaderViewController *)reader{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
